// src/main/java/tech/aistar/service/OrderServiceImpl.java
package tech.aistar.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.aistar.mapper.OrderMapper;
import tech.aistar.pojo.Order;
import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public List<Order> getOrderList(String orderId, String buyerName, Integer orderStatus, Integer page, Integer size) {
        Integer offset = (page - 1) * size;
        return orderMapper.selectOrderList(orderId, buyerName, orderStatus, offset, size);
    }

    @Override
    public Long getOrderCount(String orderId, String buyerName, Integer orderStatus) {
        return orderMapper.countOrders(orderId, buyerName, orderStatus);
    }

    @Override
    public Order getOrderById(String orderId) {
        return orderMapper.findByOrderId(orderId);
    }

    @Override
    @Transactional
    public boolean cancelOrder(String orderId) {
        try {
            // 1. 获取订单信息
            Order order = orderMapper.findByOrderId(orderId);
            if (order == null) {
                return false;
            }

            // 2. 只有待支付和已支付的订单可以取消
            if (order.getOrderStatus() != 0 && order.getOrderStatus() != 1) {
                return false;
            }

            // 3. 如果订单已支付，需要退款给买家
            if (order.getOrderStatus() == 1) {
                // 退款给买家
                int refundResult = orderMapper.refundToUser(order.getUserId(), order.getTotalAmount());
                if (refundResult <= 0) {
                    throw new RuntimeException("退款失败");
                }
            }

            // 4. 更新订单状态为已取消
            int updateResult = orderMapper.cancelOrder(orderId);
            return updateResult > 0;
        } catch (Exception e) {
            throw new RuntimeException("取消订单失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean completeOrder(String orderId) {
        try {
            // 1. 获取订单信息
            Order order = orderMapper.findByOrderId(orderId);
            if (order == null) {
                return false;
            }

            // 2. 只有已发货的订单可以完成
            if (order.getOrderStatus() != 2) {
                return false;
            }

            // 3. 解析卖家ID并从order_id中获取
            String sellerIdStr = order.getSellerId();
            if (sellerIdStr == null || sellerIdStr.isEmpty()) {
                throw new RuntimeException("无法解析卖家ID");
            }

            Integer sellerId = Integer.parseInt(sellerIdStr);

            // 4. 打款给卖家（手续费为0，全额打款）
            int payResult = orderMapper.payToSeller(sellerId, order.getTotalAmount());
            if (payResult <= 0) {
                throw new RuntimeException("打款给卖家失败");
            }

            // 5. 更新订单状态为已完成
            int updateResult = orderMapper.completeOrder(orderId);
            return updateResult > 0;
        } catch (Exception e) {
            throw new RuntimeException("完成订单失败: " + e.getMessage());
        }
    }
}